/****************************************************************************************************
* 版权所有： Copyright (c) 2015-2022 鑫光家纺. All rights reserved.
* 作    者： 半   饱
* 创建日期： 2022/8/8
* 界面功能： <#界面功能#>
****************************************************************************************************/
#import "BBAlertSheetController.h"
#import "BBAlertAction.h"
#import "BBAlertConfiguration.h"

#if __has_include(<Masonry/Masonry.h>)
#import <Masonry/Masonry.h>
#else
#import "Masonry.h"
#endif

@interface BBAlertSheetController ()
#pragma mark - 界面元素

@property (nonatomic,strong) UIView *alertView;

@property (nonatomic,strong) UILabel *titleLabel;

@property (nonatomic,strong) UILabel *messageLabel;

@property (nonatomic,strong) UIView *acrossSpliteView;

#pragma mark - 内置变量

/// 事件数组
@property  (nonatomic,strong) NSMutableArray *actionArray;

/// 取消事件
@property (nonatomic,strong) BBAlertAction *cancelAction;

/// 标题
@property (nonatomic,copy) NSString *titleString;

/// 信息
@property (nonatomic,copy) NSString *messageString;

/// 配置
@property (nonatomic,strong) BBAlertConfiguration *alertConfiguration;

@end

@implementation BBAlertSheetController

+ (instancetype)alertViewControllerWithTitle:(NSString *)title withMessage:(NSString *)message  withConfiguration:(nonnull BBAlertConfiguration *)alertConfiguration {
    BBAlertSheetController *instance = [[self alloc] init];
//    if (title.length < 1 && message.length < 1) {
//        NSAssert(NO, @"Title和Message必须有一个有值");
//    }
    //这个必须放在最前面，不然不能正常执行到
    instance.alertConfiguration = alertConfiguration;
    instance.titleString = title;
    instance.messageString = message;
    //设置view.backgroundColor就已经开始执行viewDidLoad方法
    instance.view.backgroundColor = [UIColor colorWithHex:0x333333 alpha:0.5f];
    instance.modalPresentationStyle =  UIModalPresentationOverCurrentContext;
    return instance;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self layerUI];
}

- (void)addAction:(BBAlertAction *)alertAction {
    if (!self.actionArray) {
        self.actionArray = [NSMutableArray array];
    }
    if (alertAction.actionType == BBAlertActionTypeCancel) {
        if (self.cancelAction) {
            NSAssert(NO, @"AlertSheetController最多只能设置一个Cancel Action");
            return;
        }
        self.cancelAction = alertAction;
    } else {
        [self.actionArray addObject:alertAction];
    }
}

- (void)setTitleString:(NSString *)titleString {
    _titleString = titleString;
    self.titleLabel.text = titleString;
    if (titleString.length < 1) {
        self.titleLabel.hidden = YES;
    }
}

- (void)setMessageString:(NSString *)messageString {
    _messageString = messageString;
    self.messageLabel.text = messageString;
    if (messageString.length < 1) {
        self.messageLabel.hidden = YES;
    } else {
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = self.alertConfiguration.messageLineSpace;
        style.alignment = (NSInteger)self.alertConfiguration.messageTextAlignment;
        style.lineBreakMode = NSLineBreakByTruncatingTail;
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:messageString];
        [attributedString addAttributes:@{NSForegroundColorAttributeName:self.alertConfiguration.messageColor,NSFontAttributeName:self.alertConfiguration.messageFont,NSParagraphStyleAttributeName:style}  range:NSMakeRange(0, messageString.length)];
        self.messageLabel.attributedText = attributedString;
    }
}

- (void)addSubUI {
    [self.view addSubview:self.alertView];
    [self.alertView addSubview:self.titleLabel];
    [self.alertView addSubview:self.messageLabel];
    [self.alertView addSubview:self.acrossSpliteView];
}

- (void)layerUI {
    CGFloat offsetBottom = BBAlertView_IsBangsScreen? 31.f : 0.f;
    [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.bottom.offset(0);
    }];
    
    if (self.titleString.length < 1) {
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.left.offset(16);
            make.right.offset(-16);
            make.height.offset(0);
        }];
        self.titleLabel.hidden = YES;
    } else  {
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(10);
            make.left.offset(16);
            make.right.offset(-16);
        }];
    }
    if (self.messageString.length < 1) {
        [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleLabel.mas_bottom).offset(0);
            make.left.offset(0);
            make.right.offset(0);
            make.height.offset(0);
        }];
    }
    [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
        make.left.offset(15);
        make.right.offset(-15);
    }];
    if (self.actionArray.count < 1) {
        if (self.cancelAction) {
            [self.acrossSpliteView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.offset(self.alertConfiguration.acrossHeight);
                make.left.right.offset(0);
                make.top.equalTo(self.messageLabel.mas_bottom).offset(0);
            }];
            [self showCancelActionButton];
        } else {
            [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.offset(-10 - offsetBottom);
            }];
        }
        return;
    }
    [self showActionButton];
    [self showCancelActionButton];
}

- (UIView *)alertView {
    if (!_alertView) {
        _alertView = [[UIView alloc] init];
        _alertView.backgroundColor = self.alertConfiguration.alertViewBackgroundColor;
        _alertView.layer.cornerRadius = self.alertConfiguration.cornerRadius;
        _alertView.layer.masksToBounds = YES;
        if (self.alertConfiguration.alertViewBackgroundImage) {
            self.view.contentMode = UIViewContentModeScaleAspectFit;
            _alertView.layer.contents = (__bridge id _Nullable)self.alertConfiguration.alertViewBackgroundImage.CGImage;
        }
    }
    return _alertView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = self.alertConfiguration.titleColor;
        _titleLabel.font = self.alertConfiguration.titleFont;
        _titleLabel.textAlignment = (NSInteger)self.alertConfiguration.titleTextAlignment;
    }
    return _titleLabel;
}

- (UILabel *)messageLabel {
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc] init];
        _messageLabel.textColor = self.alertConfiguration.messageColor;
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.font = self.alertConfiguration.messageFont;
        _messageLabel.numberOfLines = self.alertConfiguration.messageLineCount;
    }
    return _messageLabel;
}

- (UIView *)acrossSpliteView {
    if (!_acrossSpliteView) {
        _acrossSpliteView = [[UIView alloc] init];
        _acrossSpliteView.backgroundColor = self.alertConfiguration.acrossColor;
        _acrossSpliteView.hidden = self.alertConfiguration.acrossHidden;
    }
    return _acrossSpliteView;
}

- (void)showActionButton {
    if (self.actionArray.count < 1) {
        return;
    }
    NSMutableArray *controlArray = [NSMutableArray array];
    NSInteger index = 0;
    UIView *previousView = nil;
    for (BBAlertAction *itemAction in self.actionArray) {
        UIView *itemActionView = [[UIView alloc] init];
        itemActionView.tag = 10000 + index;
        UIView *splitView = [[UIView alloc] init];
        splitView.backgroundColor = self.alertConfiguration.acrossColor;
        [itemActionView addSubview:splitView];
        UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [itemButton setTitle:itemAction.actionTitle forState:UIControlStateNormal];
        itemButton.tag = 1000 + index;
        if (itemAction.actionType == BBAlertActionTypeDefault) {
            [itemButton setTitleColor:self.alertConfiguration.typeDefaultColor forState:UIControlStateNormal];
            itemButton.titleLabel.font = self.alertConfiguration.typeDefaultFont;
            itemButton.backgroundColor = self.alertConfiguration.typeDefaultBackgroundColor;
            if (self.alertConfiguration.typeDefaultBackgroundImage) {
                [itemButton setBackgroundImage:self.alertConfiguration.typeDefaultBackgroundImage forState:UIControlStateNormal];
            }
        } else {
            [itemButton setTitleColor:self.alertConfiguration.typeCustomColor forState:UIControlStateNormal];
            itemButton.titleLabel.font = self.alertConfiguration.typeCustomFont;
            itemButton.backgroundColor = self.alertConfiguration.typeCustomBackgroundColor;
            if (self.alertConfiguration.typeCustomBackgroundImage) {
                [itemButton setBackgroundImage:self.alertConfiguration.typeCustomBackgroundImage forState:UIControlStateNormal];
            }
        }
        if (itemAction.actionIconImage) {
            UIImage *actionImage = [itemAction.actionIconImage imageScaleWithSize:self.alertConfiguration.actionImageSize];
            [itemButton setImage:actionImage forState:UIControlStateNormal];
        }
        itemButton.layer.masksToBounds = YES;//有些影响性能，但可以把背景图片也同样切成圆角
        itemButton.layer.cornerRadius = self.alertConfiguration.actionCornerRadius;
        [itemButton addTarget:self action:@selector(itemButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [itemActionView addSubview:itemButton];
        [self.alertView addSubview:itemActionView];
       
        CGFloat offsetBottom = BBAlertView_IsBangsScreen? 31.f : 0.f;
        //布局顺序：View -> splitView -> button
        [itemActionView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (previousView) {
                make.top.equalTo(previousView.mas_bottom).offset(0);
            } else {
                make.top.equalTo(self.messageLabel.mas_bottom).offset(10);
            }
            make.left.right.offset(0);
            make.height.offset(self.alertConfiguration.actionHeight);
            if (index+1 == self.actionArray.count && !self.cancelAction) {
                make.bottom.offset(-10 - offsetBottom);
            }
        }];
        
        if (index == 0 && (self.messageString.length < 1 && self.titleString.length < 1)) {
            splitView.hidden = YES;
        } else {
            [splitView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.offset(0);
                make.left.right.offset(0);
                make.height.offset(self.alertConfiguration.verticalWidth);
            }];
        }
        [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(1);
            make.height.offset(self.alertConfiguration.actionHeight);
            make.left.offset(self.alertConfiguration.actionEdgeInsets.left);
            make.right.offset(-self.alertConfiguration.actionEdgeInsets.right);
        }];
        //图片布局
        [itemButton buttonWithEdgeInsetsStyle:itemAction.actionEdgeInsetStyle withImageTitleSpace:itemAction.textAndImageSpace];
        
        if (index + 1 == self.actionArray.count) {
            if (self.cancelAction) {
                [self.acrossSpliteView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(itemActionView.mas_bottom).offset(0.f);
                    make.left.right.offset(0);
                    make.height.offset(self.alertConfiguration.acrossHeight);
                }];
                self.acrossSpliteView.hidden = self.alertConfiguration.acrossHidden;
            } else {
                self.acrossSpliteView.hidden = YES;
            }
        }
        previousView = itemActionView;
        index++;
    }
}

- (void)showCancelActionButton {
    if (!self.cancelAction) {
        return;
    }
    CGFloat offsetBottom = BBAlertView_IsBangsScreen? 31.f : 0.f;
    UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [itemButton setTitle:self.cancelAction.actionTitle forState:UIControlStateNormal];
    [itemButton setTitleColor:self.alertConfiguration.typeCancelColor forState:UIControlStateNormal];
    itemButton.titleLabel.font = self.alertConfiguration.typeCancelFont;
    itemButton.backgroundColor = self.alertConfiguration.typeCancelBackgroundColor;
    itemButton.layer.masksToBounds = YES;//有些影响性能，但可以把背景图片也同样切成圆角
    itemButton.layer.cornerRadius = self.alertConfiguration.actionCornerRadius;
    itemButton.tag = 99999;
    [itemButton addTarget:self action:@selector(itemButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    if (self.cancelAction.actionIconImage) {
        UIImage *actionImage = [self.cancelAction.actionIconImage imageScaleWithSize:self.alertConfiguration.actionImageSize];
        [itemButton setImage:actionImage forState:UIControlStateNormal];
    }
    if (self.alertConfiguration.typeCancelBackgroundImage) {
        [itemButton setBackgroundImage:self.alertConfiguration.typeCancelBackgroundImage forState:UIControlStateNormal];
    }
    [self.alertView addSubview:itemButton];
    [itemButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(0);
        make.top.equalTo(self.acrossSpliteView.mas_bottom).offset(0);
        make.height.offset(self.alertConfiguration.actionHeight + offsetBottom);
    }];
    if (self.cancelAction.actionIconImage) {
        [itemButton buttonWithEdgeInsetsStyle:self.cancelAction.actionEdgeInsetStyle withImageTitleSpace:self.cancelAction.textAndImageSpace];
    }
}

- (void)itemButtonEvent:(UIButton *)sender {
    if (sender.tag == 99999) {
        if (self.cancelAction.actionBlock) {
            self.cancelAction.actionBlock();
        }
        [self dismissViewControllerAnimated:NO completion:nil];
        return;
    }
    
    BBAlertAction *alertAction  = self.actionArray[sender.tag - 1000];
    if (alertAction.actionType != BBAlertActionTypeCustom) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    if (alertAction.actionBlock) {
        alertAction.actionBlock();
    }
}
@end
